//
//  LogisticsLocationViewController.m
//  Logistics
//
//  Created by 锋 on 2018/1/13.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "LogisticsLocationViewController.h"
#import <QMapKit/QMapKit.h>
#import <QMapSearchKit/QMapSearchKit.h>

@interface LogisticsLocationViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, QMapViewDelegate, QMSSearchDelegate>
@property (nonatomic, strong) UITableView *addressTableView;
@property (nonatomic, strong) NSMutableArray *addressArr;
@property (nonatomic, strong) NSMutableArray *filterArray;
@property (nonatomic, strong) NSMutableArray *selectArr;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) QMSSearcher *searcher;
@property (nonatomic, strong) QMapView *mapView;
@property (nonatomic, assign) NSInteger searchType;
@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, strong) NSMutableArray<id <QAnnotation> > *annotations;
@end

@implementation LogisticsLocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _searchType = 1;
    self.selectArr = @[].mutableCopy;
    self.addressArr = @[].mutableCopy;
    self.filterArray = @[].mutableCopy;
    [self setupUI];
    [self setupAddressTableView];

    // Do any additional setup after loading the view.
}

- (void)setupUI {
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(ensureLocation)];
    [rightBtn setTintColor:[UIColor whiteColor]];
    self.navigationItem.rightBarButtonItem = rightBtn;
    UIBarButtonItem *leftBtn = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(goBack)];
    [leftBtn setTintColor:[UIColor whiteColor]];
    self.navigationItem.leftBarButtonItem = leftBtn;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"选择位置";
    self.view.backgroundColor = ThemeColor;
    //搜索
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45)];
    _searchBar.backgroundColor = [UIColor whiteColor];
    _searchBar.placeholder = @"搜索地点";
    _searchBar.delegate = self;
    [self.view addSubview:_searchBar];
    self.searcher = [[QMSSearcher alloc] init];
    [self.searcher setDelegate:self];
    //地图
    self.mapView = [[QMapView alloc] initWithFrame:CGRectMake(0, 45, SCREEN_WIDTH, self.view.frame.size.height/2 + 20)];
    self.mapView.delegate = self;
    //开启定位
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = QUserTrackingModeFollow;
    [self.view addSubview:self.mapView];
    //中心定位大头针
    UIButton *centerLocationBtn = [ZCControl createButtonWithFrame:CGRectMake(0, 0, 40, 40) ImageName:@"dingwei(2)" Target:self Action:@selector(onClickMyLocationBtn) Title:nil Font:12];
    centerLocationBtn.center = CGPointMake(_mapView.center.x, (self.view.frame.size.height/2 - 45)/2-20);
    [self.mapView addSubview:centerLocationBtn];
    //追踪定位
    UIButton *myLocationBtn = [ZCControl createButtonWithFrame:CGRectMake(5, self.view.frame.size.height/2 - 110, 40, 40) ImageName:@"dingwei2" Target:self Action:@selector(onClickMyLocationBtn) Title:nil Font:12];
    [self.mapView addSubview:myLocationBtn];
    [self searchCoordinate];
}

- (void)setupAddressTableView {
    CGFloat height = self.view.frame.size.height/2;
    self.addressTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - height, SCREEN_WIDTH, height-STA_NAV_HEIGHT) style:UITableViewStyleGrouped];
    _addressTableView.delegate = self;
    _addressTableView.dataSource = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.000001)];
    view.backgroundColor = [UIColor whiteColor];
    _addressTableView.tableHeaderView = view;
    _addressTableView.tableFooterView = view;
    _addressTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_addressTableView];
}

// MARK:tableview的方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _filterArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.000001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    }

    UIButton *selectBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-30, 0, 30, 44) ImageName:@"" Target:self Action:@selector(onClickSelectBtn) Title:nil Font:10];
    selectBtn.tag = indexPath.row+10;
    [selectBtn setImage:[UIImage imageNamed:@"xuanze"] forState:UIControlStateSelected];
    [selectBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [cell.contentView addSubview:selectBtn];
    selectBtn.selected = [_selectArr[indexPath.row] boolValue];
    
    QMSSuggestionPoiData *poi = _filterArray[indexPath.row];
    cell.textLabel.text = poi.title;
    cell.detailTextLabel.text = poi.address;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    _selectArr[indexPath.row] = @(YES);
    for (int i = 0; i < _selectArr.count; i++) {
        if (indexPath.row != i) {
            _selectArr[i] = @(NO);
        }
    }
    [_addressTableView reloadData];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)onClickSelectBtn {
    
}

- (void)ensureLocation {
    NSInteger index = 0;
    for (int i = 0; i < _selectArr.count; i++) {
        BOOL selectStatus = [_selectArr[i] boolValue];
        if (selectStatus) {
            index = i;
        }
    }
    QMSSuggestionPoiData *poi = _filterArray[index];
    self.locationBlock([NSString stringWithFormat:@"%lf", poi.location.latitude], [NSString stringWithFormat:@"%lf", poi.location.longitude], poi.address);
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [_searchBar resignFirstResponder];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if ([searchText isEqualToString:@""]) {
        [self searchCoordinate];
    } else {
        QMSSuggestionSearchOption *sugSearchOption = [[QMSSuggestionSearchOption alloc] init];
        [sugSearchOption setKeyword:searchText];
        //    //设置此参数会限制检索城市
        //    [sugSearchOption setRegion:@"北京"];
        //    //此接口同样支持检索分类
        //    [sugSearchOption setFilterByCategories:@"公交站", nil];
        [self.searcher searchWithSuggestionSearchOption:sugSearchOption];
    }
}

//关键字的补完与提示回调接口
- (void)searchWithSuggestionSearchOption:(QMSSuggestionSearchOption *)
suggestionSearchOption didReceiveResult:(QMSSuggestionResult *)suggestionSearchResult {
    _searchType = 2;
    [_filterArray removeAllObjects];
    [_selectArr removeAllObjects];
    for (int i = 0; i < suggestionSearchResult.dataArray.count; i++) {
        QMSSuggestionPoiData *poi = suggestionSearchResult.dataArray[i];
        [_filterArray addObject:poi];
        [_selectArr addObject:@(NO)];
    }
    [_addressTableView reloadData];
}

- (void)searchWithReverseGeoCodeSearchOption:(QMSReverseGeoCodeSearchOption *)
reverseGeoCodeSearchOption didReceiveResult:(QMSReverseGeoCodeSearchResult *)
reverseGeoCodeSearchResult {
    _searchType = 1;
    [_filterArray removeAllObjects];
    [_selectArr removeAllObjects];
    for (int i = 0; i < reverseGeoCodeSearchResult.poisArray.count; i++) {
        QMSSuggestionPoiData *poi = reverseGeoCodeSearchResult.poisArray[i];
        [_filterArray addObject:poi];
        [_selectArr addObject:@(NO)];
    }
    [_addressTableView reloadData];
}

- (void)onClickMyLocationBtn {
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = QUserTrackingModeFollow;
    [self searchCoordinate];
}

//<QMapViewDelegate >中的定位回调函数
- (void)mapViewWillStartLocatingUser:(QMapView *)mapView
{
    NSLog(@"%s", __FUNCTION__);
}

- (void)mapViewDidStopLocatingUser:(QMapView *)mapView
{
    NSLog(@"%s", __FUNCTION__);
    
}

/**
 * @brief 用户位置更新后，会调用此函数
 * @param mapView 地图View
 * @param userLocation 新的用户位置
 * @param fromHeading 是否为heading 变化触发，如果为location变化触发,则为NO
 */
- (void)mapView:(QMapView *)mapView didUpdateUserLocation:(QUserLocation *)userLocation fromHeading:(BOOL)fromHeading
{
    NSLog(@"%s fromHeading = %d, location = %@, heading = %@", __FUNCTION__, fromHeading, userLocation.location, userLocation.heading);
    if (_mapView.centerCoordinate.latitude != _coordinate.latitude || _mapView.centerCoordinate.longitude != _coordinate.longitude) {
        if (_searchType == 1) {
            [self searchCoordinate];
        }
    }
    _coordinate = _mapView.centerCoordinate;
}

/**
 * @brief  定位失败后，会调用此函数
 * @param mapView 地图View
 * @param error 错误号，参考CLError.h中定义的错误号
 */
- (void)mapView:(QMapView *)mapView didFailToLocateUserWithError:(NSError *)error
{
    NSLog(@"%s error = %@", __FUNCTION__, error);
}

/**
 * @brief 定位时的userTrackingMode 改变时delegate调用此函数
 *  @param mapView 地图View
 *  @param mode QMUserTrackingMode
 *  @param animated 是否有动画
 */
- (void)mapView:(QMapView *)mapView didChangeUserTrackingMode:(QUserTrackingMode)mode animated:(BOOL)animated
{
    NSLog(@"%s mode = %d, animated = %d", __FUNCTION__, mode, animated);
    
}

- (void)searchCoordinate {
    QMSReverseGeoCodeSearchOption *option = [[QMSReverseGeoCodeSearchOption alloc] init];
    option.location = [NSString stringWithFormat:@"%lf,%lf", _mapView.centerCoordinate.latitude, _mapView.centerCoordinate.longitude];
    //返回坐标点附近poi列表
    [option setGet_poi:YES];
    [self.searcher searchWithReverseGeoCodeSearchOption:option];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
